import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

public class ThreadDemo10 {
    public static void main(String[] args) throws InterruptedException {
        //1. 构造方法中写10，表示同步10个线程
        //CountDownLatch latch=new CountDownLatch(10);
        Semaphore semaphore=new Semaphore(10);
        //创建10个线程模拟下载任务
        for(int i=0;i<10;i++){
            int id=i;
            Thread t=new Thread(()->{
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Random random=new Random();
                int time=(random.nextInt(5)+1)*1000;
                System.out.println("线程"+ id + "开始下载");
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程"+ id +"结束下载");
                //2.每个线程执行完，都要告诉countDownLatch，执行完毕
                //latch.countDown();
                semaphore.release();
            });
            t.start();
        }
        //3.通过await方法来等待所有任务结束，也就是countDown被调用了十次
        //latch.await();
        //此处就要确保主线程不会跟别的线程争夺信号量
        semaphore.acquire(10);
        System.out.println("所有任务都已经执行完毕了！");
    }

}
